package com.bank.um.controller;

import com.bank.entity.Member;
import com.bank.entity.constant.ResponseEnum;
import com.bank.entity.vo.Response;
import com.bank.um.service.MemberService;
import com.bank.utils.*;
import com.baomidou.mybatisplus.extension.api.R;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.bank.utils.ValidatorUtils.*;

/**
 * @author: Lixy
 * @email: 1908598362@qq.com
 * @date: 2021/12/31 星期五 20:27
 */
@RestController
@RequestMapping("/member")
@CrossOrigin
@Aspect
public class MemberController {

    @Autowired
    private MemberService memberService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @PostMapping("/regist")
    public Response regist(Long age, String name, Long memcardnum, String phone, String password) {
        String Md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        //String sms = sendService.sendSms(phone);
        //Response response = new Response();
        int row = memberService.addMember(age, name, memcardnum, phone, Md5Password);
        if (Md5Password.isEmpty()) {
            Response response1 = Response.response1(ResponseEnum.ERROR, -1, "密码不能为空");
            return response1;
        }
        if (age == null) {
            Response response1 = Response.response1(ResponseEnum.ERROR, -1, "年龄不能为空");
            return response1;
        }
        if (name == null) {
            Response response1 = Response.response1(ResponseEnum.ERROR, -1, "姓名不能为空");
            return response1;
        }
        if (memcardnum == null) {
            Response response1 = Response.response1(ResponseEnum.ERROR, -1, "身份证不能为空");
            return response1;
        }
        if (phone == null) {
            Response response1 = Response.response1(ResponseEnum.ERROR, -1, "手机号不能为空");
            return response1;
        }
        if (row > 0) {
            Response response1 = Response.response1(ResponseEnum.SUCCESS, row, "注册成功");
            return response1;

        } else {
            Response response1 = Response.response1(ResponseEnum.ERROR, -1, "请检查验证码是否正确或网络是否正常");
            return response1;
        }
    }


    @PostMapping("/loginByPass")
    public Response loginByPass(@Valid String name, String password, HttpServletResponse httpServletResponse, HttpServletRequest httpServletRequest) {
        String Md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        //Response response = new Response();
        Member member = memberService.SelectByPass(name, Md5Password);
        if (member != null) {
            //jjwt设置Token令牌解决短会话问题
            //httpServletResponse.setHeader("Token", JwtUtils.getJwtToken(String.valueOf(member.getId())));

            //用户信息存入Session中，通过Cookie存储
            String uuid = UUIDUtil.uuid();
            System.out.println(uuid);
            //httpServletRequest.getSession().setAttribute(uuid,member);
            redisTemplate.opsForValue().set("member:" + uuid, member, 1800, TimeUnit.SECONDS);
            CookieUtils.setCookie(httpServletRequest, httpServletResponse, "MemeberUUID", uuid);
            return Response.response1(ResponseEnum.SUCCESS, member, "登陆成功");
        } else {
            return Response.response3(ResponseEnum.CHECK_USERNAME_AND_PASSWORD_ERROR, ResponseEnum.CHECK_USERNAME_AND_PASSWORD_ERROR.getMsg());
        }
    }

    @PostMapping("/loginByPhone")
    public Response loginByPhone(@Valid String phone, String code, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String message) throws Exception {
        //Response response = new Response();
        if (!ValidatorUtils.isPhone(phone)) {
            return Response.response1(ResponseEnum.MOBILE_STATUS_ERROR, -1, ResponseEnum.MOBILE_STATUS_ERROR.getMsg());
        }
        Member member = memberService.SelectByPhone(phone);
        boolean doget = memberService.getVcode(member.getPhone(), code);
        if (!doget) {
            return Response.response1(ResponseEnum.ERROR, -1, "验证码选择错误，请重试");
        }
        boolean messagesucs = memberService.getPcode(phone, message);
        if (messagesucs) {
            String uuid = UUIDUtil.uuid();
            //httpServletRequest.getSession().setAttribute(uuid,member);
            redisTemplate.opsForValue().set("member:" + uuid, member, 1800, TimeUnit.SECONDS);
            CookieUtils.setCookie(httpServletRequest, httpServletResponse, "MemeberUUID", uuid);
            return Response.response1(ResponseEnum.SUCCESS, member, "验证成功，正在登陆");
        } else {
            return Response.response1(ResponseEnum.VALIDATOR_ERROR, -1, ResponseEnum.VALIDATOR_ERROR.getMsg());
        }
    }

    @GetMapping("/verifiyCode")
    public Response verifyCode(String phone) {
        String countKey = phone + "count";
        String codeKey = phone + "code";
        //Response response = new Response();
        String pcode = GetCode();
        String code01 = GetFakeCode();
        String code02 = GetFakeCode();

        if (redisTemplate.opsForValue().get(countKey) == null) {
            redisTemplate.opsForValue().set(countKey, "1", getRemainSecondsDay(), TimeUnit.SECONDS);
        }
//        } else if (Integer.parseInt(String.valueOf(redisTemplate.opsForValue().get(countKey))) <= 5) {
//            redisTemplate.opsForValue().increment(countKey);
//        } else {
//            return Response.response3(ResponseEnum.ERROR, "今日验证码发送次数已用完");
//        }
        redisTemplate.opsForValue().set(codeKey, pcode, 60, TimeUnit.SECONDS);
        return Response.response1(ResponseEnum.SUCCESS, "true:" + pcode + "fake:" + code01 + "fake:" + code02, "本地验证码发送成功");
    }

    @PostMapping("/changePhone")
    public Response changePhoneMsg(String name, String password, String phone, String message) {
        String Md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
        Member member = memberService.SelectByPass(name, Md5Password);
        if (member == null) {
            return Response.response1(ResponseEnum.CHECK_USERNAME_AND_PASSWORD_ERROR, -1, ResponseEnum.CHECK_USERNAME_AND_PASSWORD_ERROR.getMsg());
        }
        //boolean doget = memberService.getVcode(member.getPhone(), code);
        boolean messagesucs = memberService.getPcode(phone, message);
        if (messagesucs) {
            int row = memberService.UpdateMemPhone(member, phone);
            if (row > 0) {
                return Response.response3(ResponseEnum.SUCCESS, "手机号修改成功");
            } else {
                return Response.response3(ResponseEnum.ERROR, "手机号修改失败请检查是否填写了正确的手机号");
            }
        } else {
            return Response.response1(ResponseEnum.VALIDATOR_ERROR, -1, ResponseEnum.VALIDATOR_ERROR.getMsg());
        }
    }

    @PostMapping("/changNameOrPass")
    public Response changeNameOrPassMsg(String phone, String newPassword, String newName, String message, HttpServletRequest request) {
        if (!ValidatorUtils.isPhone(phone)) {
            return Response.response1(ResponseEnum.MOBILE_STATUS_ERROR, -1, ResponseEnum.MOBILE_STATUS_ERROR.getMsg());
        }
        Member member = memberService.SelectByPhone(phone);
        String uuid = CookieUtils.getCookieValue(request, "MemeberUUID");
        //boolean doget = memberService.getVcode(member.getPhone(), code);
        boolean messagesucs = memberService.getPcode(phone, message);
        if (messagesucs) {
            String Md5Password = DigestUtils.md5DigestAsHex(newPassword.getBytes());
            int row = memberService.UpdateMemNameOrPass(member, newName, Md5Password, uuid);
            if (row > 0) {
                return Response.response3(ResponseEnum.SUCCESS, "修改用户名或密码成功,请重新登录");
            } else {
                return Response.response3(ResponseEnum.ERROR, "修改失败请重试");
            }
        } else {
            return Response.response1(ResponseEnum.VALIDATOR_ERROR, message, ResponseEnum.VALIDATOR_ERROR.getMsg());
        }
    }


    @GetMapping("/verifiyMessage")
    public Response verifyMessage(String phone) throws Exception {
        String codeKey = phone + "message";
        String message = SmsUtils.SendSms(phone);
        redisTemplate.opsForValue().set(codeKey, message, 60, TimeUnit.SECONDS);
        return Response.response1(ResponseEnum.SUCCESS, message, "验证码发送成功");
    }


    @PostMapping("/tologin")
    public Response toLogin(String uuid, HttpServletResponse response, HttpServletRequest request) {
        Member member = memberService.SelectByCoolredis(uuid, response, request);
        if (member != null) {
            return Response.response2(ResponseEnum.SUCCESS, member);
        } else {
            return Response.response1(ResponseEnum.USER_NOT_LOGIN_ERROR, uuid, ResponseEnum.USER_NOT_LOGIN_ERROR.getMsg());
        }
    }

    @PostMapping("/uidToLogin")
    public Response uidToLogin(Member member, HttpServletResponse response, HttpServletRequest request) {
        String uuid = memberService.addByCookie(request, response, member);
        if (uuid != null) {
            return Response.response2(ResponseEnum.SUCCESS, uuid);
        } else {
            return Response.response3(ResponseEnum.USER_NOT_LOGIN_ERROR, ResponseEnum.USER_NOT_LOGIN_ERROR.getMsg());
        }
    }

    @Pointcut(value = "execution(* com.bank.um.controller..*(..))")
    public void Point() {
    }

    @Around(value = "Point()")
    public Response around(JoinPoint point) {
        String methodName = point.getSignature().getName();
        if (!methodName.equals("loginByPass")) {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String uuid = CookieUtils.getCookieValue(request, "MemeberUUID");
            Member member = ((Member) redisTemplate.opsForValue().get("member:" + uuid));
            if (member == null) {
                return Response.response1(ResponseEnum.USER_NOT_LOGIN_ERROR,-1,ResponseEnum.USER_NOT_LOGIN_ERROR.getMsg());
            }else {
                return Response.response2(ResponseEnum.SUCCESS,member);
            }
        }else {
            return Response.response3(ResponseEnum.SUCCESS,ResponseEnum.SUCCESS.getMsg());
        }
    }
}

